<template>
  <div id="list">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图区域 -->
    <el-card>
      <!-- 搜索区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="query_info.query"
            clearable
            @clear="get_goods_list"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="get_goods_list"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="go_add_goods">添加商品</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="goods_list" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column
          label="商品名称"
          prop="goods_name"
          class="goods_name"
        ></el-table-column>
        <el-table-column
          label="商品价格(元)"
          prop="goods_price"
          width="110px"
        ></el-table-column>
        <el-table-column
          label="商品重量"
          prop="goods_weight"
          width="95px"
        ></el-table-column>
        <el-table-column label="创建时间" prop="add_time" width="170px">
          <template slot-scope="scope">
            {{ scope.row.add_time | date_formate }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="130px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="edit_goods_id(scope.row.goods_id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="del_goods_id(scope.row.goods_id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="query_info.pagenum"
        :page-sizes="[10, 30, 50, 100]"
        :page-size="query_info.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 编辑商品区域 -->
    <el-dialog
      title="编辑商品"
      :visible.sync="edit_dialog_visible"
      width="50%"
      @close="edit_dialog_close"
    >
      <!-- 表单区域 -->
      <el-form
        :model="edit_form"
        :rules="edit_form_rules"
        ref="edit_form_ref"
        label-width="130px"
        label-position="left"
      >
        <el-form-item label="商品名称" prop="goods_name">
          <el-input v-model="edit_form.goods_name"></el-input>
        </el-form-item>
        <el-form-item label="商品价格（元）" prop="goods_price">
          <el-input v-model="edit_form.goods_price" type="number"></el-input>
        </el-form-item>
        <el-form-item label="商品重量" prop="goods_weight">
          <el-input v-model="edit_form.goods_weight" type="number"></el-input>
        </el-form-item>
        <el-form-item label="商品数量" prop="goods_weight">
          <el-input v-model="edit_form.goods_number" type="number"></el-input>
        </el-form-item>
        <el-form-item label="商品分类" prop="">
          <el-cascader
            expand-trigger="hover"
            :props="cascader_props"
            v-model="selected_keys"
            :options="parents_list"
            @change="parent_cate_changed"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="edit_dialog_visible = false">取 消</el-button>
        <el-button type="primary" @click="edit_goods">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 查询参数对象
      query_info: {
        query: "",
        pagenum: 1,
        pagesize: 10,
      },
      // 商品列表
      goods_list: [],
      // 总条数
      total: 0,
      // 控制编辑商品对话框的显示与隐藏
      edit_dialog_visible: false,
      // 修改表单的数据
      edit_form: {},
      // 提交表单的验证对象
      edit_form_rules: {
        goods_name: {
          required: true,
          message: "请输入商品名称",
          trigger: "blur",
        },
        goods_price: {
          required: true,
          message: "请输入商品价格",
          trigger: "blur",
        },
        goods_weight: {
          required: true,
          message: "请输入商品重量",
          trigger: "blur",
        },
      },
      // 商品分类数据对象
      add_rule_form: {
        // 将要添加的分类名称
        cat_name: "",
        // 父级分类的 id
        cat_pid: 0,
        // 分类的等级,默认1级
        cat_level: 0,
      },
      // 父级分类的数据列表
      parents_list: [],
      // 级联选择器数据对象
      cascader_props: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        checkStrictly: true,
      },
      // 选中的父级分类Id数组
      selected_keys: [],
    };
  },
  created() {
    this.get_goods_list();
  },
  methods: {
    //   根据分页获取对应的参数列表
    async get_goods_list() {
      let { data: res } = await this.axios.get("goods", {
        params: this.query_info,
      });
      if (res.meta.status !== 200) {
        return this.message.error("获取参数失败");
      }
      this.goods_list = res.data.goods;
      this.total = res.data.total;
    },
    // 监听 pagesize 值的改变
    handleSizeChange(new_size) {
      this.query_info.pagesize = new_size;
      this.get_goods_list();
    },
    // 监听页码值的改变
    handleCurrentChange(new_num) {
      this.query_info.pagenum = new_num;
      this.get_goods_list();
    },
    // 根据 id 删除对应的商品
    async del_goods_id(id) {
      let conrfirm_result = await this.confirm(
        "此操作将永远删除该商品，是否继续？",
        "提示",
        {
          confirmButtonText: "确定",
          calcelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (conrfirm_result !== "confirm") {
        return this.message.info("已取消删除");
      }
      let { data: res } = await this.axios.delete("goods/" + id);
      if (res.meta.status !== 200) {
        return this.message.error("删除失败");
      }
      console.log(conrfirm_result);
      this.message.success("删除成功");
      this.get_goods_list();
    },
    // 获取父级分类的数据列表
    async get_parents_cate_list() {
      let { data: res } = await this.axios.get("categories", {
        params: { type: 2 },
      });
      if (res.meta.status !== 200) {
        return this.message.error("获取父级分类数据失败");
      }
      this.parents_list = res.data;
    },
    // 选择项发生变化时出发这个函数
    parent_cate_changed() {
      if (this.selected_keys.length > 0) {
        // 父级分类的 id
        this.add_rule_form.cat_pid = this.selected_keys[
          this.selected_keys.length - 1
        ];
        // 为当前分类的等级赋值
        this.add_rule_form.cat_level = this.selected_keys.length;
        return;
      } else {
        // 父级分类的 id
        this.add_rule_form.cat_pid = 0;
        // 为当前分类的等级赋值
        this.add_rule_form.cat_level = 0;
      }
    },
    // 点击按钮，展示编辑商品对话框
    async edit_goods_id(id) {
      let { data: res } = await this.axios.get("goods/" + id);
      console.log(id);
      if (res.meta.status !== 200) {
        return this.message.error("获取商品数据失败");
      }
      this.edit_form = res.data;
      this.get_parents_cate_list()
      console.log(res.data);
      this.edit_dialog_visible = true;
    },
    // 监听修改对话框关闭，清空表单
    edit_dialog_close() {
      this.edit_form = {};
    },
    // 点击按钮，跳转到添加商品
    go_add_goods() {
      this.$router.push("/goods/add");
    },
    // 点击按钮，提交修改之后的信息
    edit_goods() {
      this.$refs.edit_form_ref.validate(async (valid) => {
        if (!valid) return;
        // 提交修改用户的请求
        let { data: res } = await this.axios.put(
          `goods/${this.edit_form.cat_id}`,
          {
            goods_name: this.edit_form.goods_name,
            goods_price: this.edit_form.goods_price,
            goods_number: this.edit_form.goods_number,
            goods_weight: this.edit_form.goods_weight,
            
          },this.add_rule_form
        );
        console.log(res);
        if (res.meta.status !== 200) {
          return this.message.error("编辑商品失败");
        }
        this.message.success("编辑商品成功");
        this.get_goods_list();
        this.edit_dialog_visible = false;
      });
    },
  },
};
</script>
<style lang="less" scoped>
.el-table {
  margin-top: 15px;
}
.el-cascader {
  width: 100%;
}
</style>